<?php
/**
 * This file is part from Ewuroweb Shop
 *
 * @package EW
 * @subpackage Core
 * 
 * @author Ivan I. Atanasov <i.atanasov@viscomp.bg>
 */

abstract class EW_Form_DbObject extends EW_Form_Base {
 
    /**
     * 
     * @var unknown_type
     * @access protected
     */
    protected $_dbObject = NULL;
    
    /**
     * Default Constructor
     * 
     * @param array $options
     * @param Util_Controller_Action $controller
     * @param Vorm_Base $dbObject
     * 
     * @return EW_Form_DbObject
     */
    public function __construct($options, Ew_Core_Controller &$controller, Doctrine_Record &$dbObject) {
        $this->_dbObject = $dbObject;
        
        parent::__construct($options, $controller);
    }
    
    /**
     * Saving Form in Database.
     * 
     * Build the new db record & save.
     * 
     * @return void
     * @access protected
     */
    protected function _save() {
        $formValues = $this->getValues();
        //$dbAttributes = $this->_dbObject->getAttributes();
        try {
            
            foreach($formValues as $k=>$v) {
                /*
                if(array_key_exists($k, $dbAttributes)) {
                    $dbAttributes[$k] =$v;   
                }
                */
                $this->_dbObject->$k = $v;
            }
            
            //$this->_dbObject->setAttributes($dbAttributes);
            $this->_beforeSave();
            $this->_dbObject->save();
            $this->_afterSave();
        }
        catch(Exception $e) {
            throw $e;
        }
    }
    //==========================================================================================  
    
    /**
     * Add an Element
     * 
     * Extends parent method to auto-fill form fields when editing a db object.
     * 
     * @see Zend_Form::addElement($element, $name, $options)
     */
    function addElement($element, $name =null, $options=null) {
        parent::addElement($element, $name, $options);
        
        if(is_string($element) && $name) {
            if(isset($this->_dbObject->$name)) {
                $this->_elements[$name]->setValue($this->_dbObject->$name);
            }
        }
        else if($element instanceof Zend_Form_Element) {
           $name = $element->getName();
           if(isset($this->_dbObject->$name)) {
                $this->_elements[$name]->setValue($this->_dbObject->$name);
            }
        }
    }
    //==========================================================================================
    
}
